package com.application.sistercityapplication.main;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.application.sistercityapplication.dto.MagazineDto;
import com.application.sistercityapplication.listadapter.LoadedDocumentListAdapter;
import com.application.sistercityapplication.listadapter.LoadedDocumentListAdapter.DownloadDocumentClickListener;
import com.application.sistercityapplication.model.Magazine;
import com.application.sistercityapplication.utils.DownloadTask;
import com.application.sistercityapplication.utils.GlobalVariable;
import com.artifex.mupdfdemo.MuPDFActivity;
import com.roscopeco.ormdroid.Entity;
import com.squareup.picasso.Picasso;
import com.todddavies.components.progressbar.ProgressWheel;

public class BooksAdapter extends BaseAdapter {

	private Context context;
	private final List<MagazineDto> magazines;
	public Activity _activity;
	private int _deleteState;
	public ViewHolder viewHolder;
	private MagazineDto dto;
	private ImageView btnDel;
	private List<Integer> removeList = new ArrayList<Integer>();

	public BooksAdapter(Context context, List<MagazineDto> magazines, Activity a,int deleteState,ImageView btnDel) {
		this.context = context;
		this.magazines = magazines;
		this._activity = a;
		this._deleteState = deleteState;
		this.btnDel = btnDel;
	}

	@Override
	public int getCount() {
		return magazines.size();
	}

	@Override
	public View getView(final int position, View convertView,ViewGroup parent) {

		if (convertView == null) {
			viewHolder = new ViewHolder();
			LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			GlobalVariable gbv = new GlobalVariable();
			if(gbv.checkScreenSize(context)==gbv.LARGE_SCREEN_SIZE){
				convertView = inflater.inflate(R.layout.book_item_layout_large, null);
			}else{
				convertView = inflater.inflate(R.layout.book_item_layout, null);
			}
			viewHolder.bookImage = (ImageView) convertView.findViewById(R.id.grid_item_cover);
			viewHolder.bookClick = (RelativeLayout) convertView.findViewById(R.id.BookClick);
			viewHolder.objectSelectedImage = (ImageView) convertView.findViewById(R.id.grid_item_new);
			viewHolder.progressWheel = (ProgressWheel) convertView.findViewById(R.id.pw_spinner);
			
			
			convertView.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}
			dto = magazines.get(position);
			
			
			try{
				Picasso.with(context).load(dto.getTumbnail()).into(viewHolder.bookImage);
				
			}catch(Exception e){
				e.printStackTrace();
			}
			viewHolder.objectSelectedImage.setVisibility(View.GONE);
			
			final Magazine mag = Entity.query(Magazine.class).where("magId").eq(dto.getMagId()).execute();
			if(mag!=null){
				viewHolder.bookClick.setOnClickListener(new OnClickListener() {
					
				
					@Override
					public void onClick(View v) {
						if(_deleteState==1){ 
							
							ImageView btnSel = (ImageView) v.findViewById(R.id.grid_item_new);
							btnSel.setVisibility(View.VISIBLE);
							btnDel.setImageDrawable(_activity.getResources().getDrawable(R.drawable.del_doc_btn));
							removeList.add(mag.id);
							setRemoveList(removeList);
						}else	
						{
							Uri uri = Uri.parse(mag.path);
	
							Intent intent = new Intent(_activity, MuPDFActivity.class);
	
							intent.setAction(Intent.ACTION_VIEW);
	
							intent.setData(uri);
	
							_activity.startActivity(intent);
						}
					}
				});
				if(_deleteState==99){
					viewHolder.objectSelectedImage.setVisibility(View.VISIBLE);
				}
			}else{
				
				
				if(_deleteState==1){ 
					viewHolder.bookImage.getDrawable().mutate().setAlpha(70);
					viewHolder.bookImage.invalidate();
				}else if(_deleteState==99){
					viewHolder.bookImage.getDrawable().mutate().setAlpha(70);
					viewHolder.bookImage.invalidate();
				}else{
					viewHolder.bookClick.setOnClickListener(new DownloadDocumentClickListener(position,convertView,dto));
				}
				
			}
			
			
			btnDel.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if(_deleteState==99){
						
					}else{
						if(removeList!=null && !removeList.isEmpty()){
							for(Integer i : removeList)
							{
								Magazine mag =  Entity.query(Magazine.class).whereId(i).execute();
								mag.delete();
							}
							BooksAdapter.this.notifyDataSetChanged();
						}
				}
				
			}
		});
			
		
		return convertView;
	}
	public class DownloadDocumentClickListener implements OnClickListener{
		private int _position;
		private View view;
		private MagazineDto magazineDto;
		public DownloadDocumentClickListener(int position,View btnView,MagazineDto magazineDto){
			this._position = position;
			this.view = btnView;
			this.magazineDto = magazineDto;
		}
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub'
			
			//Toast.makeText(_context, String.valueOf(_position), Toast.LENGTH_SHORT).show();
			//viewHolder.downLoadBookBtn.setImageDrawable(_activity.getResources().getDrawable(R.drawable.download_temp));
			AlertDialog.Builder builder = new AlertDialog.Builder(
					_activity);
            builder.setTitle(_activity.getString(R.string.download_desc));
            builder.setInverseBackgroundForced(true);
            builder.setPositiveButton(_activity.getString(R.string.download_confirm),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog,
                                int which) {
                        	
                        	ImageView bookImage = (ImageView) view.findViewById(R.id.grid_item_cover);
                        	bookImage.getDrawable().mutate().setAlpha(20);
                        	bookImage.invalidate();
                        	ProgressWheel progressWheel = (ProgressWheel) view.findViewById(R.id.pw_spinner);
                        	progressWheel.setVisibility(View.VISIBLE);
                        	DownloadTask downloadTask = new DownloadTask(_activity,progressWheel,magazineDto,bookImage,BooksAdapter.this);
                			downloadTask.execute(magazineDto.getPath());
                			
                			
                        }
                    });
            builder.setNegativeButton(_activity.getString(R.string.cancel),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog,
                                int which) {
                            dialog.dismiss();
                        }
                    });
           
            AlertDialog alert = builder.create();
            alert.show();
		}
		
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return magazines.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return 0;
	}

	public class ViewHolder {
		private RelativeLayout bookClick;
		private ImageView bookImage;
		private ImageView objectSelectedImage;
		private ProgressWheel progressWheel;
	}

	public List<Integer> getRemoveList() {
		return removeList;
	}

	public void setRemoveList(List<Integer> removeList) {
		this.removeList = removeList;
	}
	
}
